//
//  SearchItem.swift
//  test1
//
//  Created by Apple on 2021/6/9.
//

/*
 参数：
 callBack(可选):使用的回调函数
 */

import SwiftUI
// 验证该url是否有效
func verifyUrl (urlString: String?) -> Bool {
   if let urlString = urlString {
       if let url = NSURL(string: urlString) {
           return UIApplication.shared.canOpenURL(url as URL)
       }
   }
   return false
}

struct SearchItem: View {
    @EnvironmentObject var modelData : HistoryListModelData
    var image: Image = Image("search")
    var width: CGFloat = UIScreen.main.bounds.width
    var height: CGFloat = UIScreen.main.bounds.height
    var callBack : ViewCallBack?
    var body: some View {
        Button(action: {
            //callBack?.search(contentUrl: modelData.Searchtext, withNewTab: false)
            //callBack?.goToView(by: .IndexView, sender: self, with: [RequestArgumentKey.wd.rawValue:modelData.Searchtext])
            callBack?.goToView(to: .IndexView, from: .SearchView, intent: .Default, with: [.wd:modelData.Searchtext])
//            if let window = UIApplication.shared.windows.first
//            {
//                if verifyUrl(urlString: modelData.Searchtext){
//                window.rootViewController = UIHostingController(rootView: SearchResultPage(url: modelData.Searchtext).environmentObject(ModelData()))
//                   window.makeKeyAndVisible()
//                } else {
//                    callBack?.search(contentUrl: "https://www.baidu.com/s?ie=utf-8&wd=" + self.modelData.Searchtext, withNewTab: false)
//                    window.rootViewController = UIHostingController(rootView: SearchResultPage(url: "https://www.baidu.com/s?ie=utf-8&wd=" + self.modelData.Searchtext).environmentObject(ModelData()))
//                    modelData.title = modelData.Searchtext + "_百度搜索"
//                    window.makeKeyAndVisible()
//                }
//            }
        }){
            image
                .resizable()
                .frame(width: 25, height: 25)
                .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10 ))
            Text(modelData.Searchtext)
                .font(.title3)
                .frame(width: 250, height: 30, alignment: .leading)
                .lineLimit(nil)
                .foregroundColor(.black)
        }
        .frame(width: width, height: 50, alignment: .leading)
        
    }
}

struct SearchItem_Previews: PreviewProvider {
    static var previews: some View {
        SearchItem()
            .environmentObject(HistoryListModelData())
    }
}
